<template>
  <el-drawer
      title="管理参与的坑组"
      size="1000px"
      direction="ltr"
      :show-close="false"
      :visible.sync="visible"
      :before-close="handleClose">
    <div id="drawer-main-box">
      <div class="table-top">
        <span style="width: 50px;">
        <el-button size="small" class="theme-button" type="primary"
                   @click="openSonDrawer('save', null)">新增</el-button>
      </span>
        <span style="width: 200px;">
        <el-input
            clearable
            v-model="keyword"
            placeholder="请输入关键词"
            @change="flashTable"
            @keydown.enter="flashTable">
        </el-input>
      </span>
      </div>

      <!--   新增/编辑弹窗   -->
      <el-drawer
          :title="mangaFormType === 'save' ? '新增漫画' : '编辑漫画'"
          size="700px"
          direction="ltr"
          :append-to-body="true"
          :show-close="false"
          :before-close="handleSonClose"
          :visible.sync="sonDrawerVisible">
        <div id="son-drawer-main-box">
          <el-form :model="mangaForm" :rules="mangaFormRules" ref="mangaForm" label-width="100px">
            <el-form-item style="width: 300px;" label="漫画名称" prop="name">
              <el-input v-model="mangaForm.name"></el-input>
            </el-form-item>
            <el-form-item style="width: 300px;" label="作者" prop="author">
              <el-input v-model="mangaForm.author"></el-input>
            </el-form-item>
            <el-form-item style="width: 300px;" label="汉化组" prop="cnTeam">
              <el-select v-if="cnTeamList.length > 0" v-model="mangaForm.tid" placeholder="请选择汉化组">
                <el-option
                    v-for="item in cnTeamList"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key">
                </el-option>
              </el-select>
              <span v-else style="border: 1px dashed gainsboro;">
                <el-button type="text" @click="$router.push({name: 'cnTeam'})">还没有加入汉化组哦！快去加入吧~</el-button>
              </span>
            </el-form-item>
            <el-form-item style="width: 500px;" label="简介" prop="about">
              <el-input type="textarea"
                        v-model="mangaForm.about"
                        :maxlength="1000"
                        :autosize="{ minRows: 2, maxRows: 5}"
              ></el-input>
            </el-form-item>
            <el-form-item style="width: 500px;" label="连载状态" prop="status">
              <el-switch
                  v-model="mangaForm.status"
                  active-color="#409eff"
                  inactive-color="#13ce66"
                  active-text="已完结"
                  inactive-text="连载中">
              </el-switch>
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <single-upload v-loading="uploadLoading" @getFile="getCover" @cleanup="cleanupCover"
                             :imageUrl="mangaForm.thumbCoverUrl ? mangaForm.thumbCoverUrl : mangaForm.coverUrl"
                             ref="cover"/>
            </el-form-item>
            <el-form-item>
              <el-button :loading="submitLoading" type="primary" @click="submitMangaForm">
                {{ mangaFormType === 'save' ? '创建' : '修改' }}
              </el-button>
              <el-button @click="resetForm('mangaForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-drawer>

      <!--   章节列表   -->
      <manga-ep-table @flashTable="flashTable" ref="mangaEpTable"/>
      <!--   坑组人员列表   -->
      <manga-member-table ref="mangaMemberTable"/>

      <!--   表格   -->
      <div id="table-box">
        <template>
          <el-table
              v-loading="loading"
              :data="tableData"
              stripe
              max-height="calc(100vh - 180px)"
              style="width: 100%">
            <el-table-column
                show-overflow-tooltip
                prop="name"
                label="漫画名">
            </el-table-column>
            <el-table-column
                show-overflow-tooltip
                prop="cnTeam"
                label="汉化组">
            </el-table-column>
            <el-table-column
                width="100"
                prop="modifyTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                width="65"
                prop="rawEpCount"
                label="生肉数"
                align="center">
            </el-table-column>
            <el-table-column
                width="65"
                prop="epCount"
                label="熟肉数"
                align="center">
            </el-table-column>
            <el-table-column
                width="60"
                prop="heat"
                label="热度"
                align="center">
            </el-table-column>
            <el-table-column
                fixed="right"
                prop="isAvailable"
                label="展示状态"
                width="78"
                align="center">
              <template slot-scope="scope">
                <el-switch
                    @change="changeStatus(scope.row)"
                    v-model="scope.row.isAvailable"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                width="250"
                align="center">
              <template slot-scope="scope">
                <el-button @click="$refs.mangaMemberTable.openWindow(scope.row)" type="text" size="small">坑组人员</el-button>
                <el-button @click="openSonDrawer('edit', scope.row)" type="text" size="small">编辑</el-button>
                <el-button style="color: #F56C6C;" @click="deleteManga(scope.row)" type="text" size="small">删除</el-button>
                <el-button type="warning" size="mini" round plain icon="el-icon-setting"
                           @click="$refs.mangaEpTable.openWindow(scope.row.mangaId, scope.row.name)">章节
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <el-pagination style="margin-left: auto; padding-top: 20px"
                     layout="total, prev, pager, next"
                     @current-change="handleCurrentChange"
                     :total="total"
                     :page-size="page.size">
      </el-pagination>
    </div>
  </el-drawer>
</template>

<script>
import {available, checkNameExist, deleted, mineMangaPage, saveManga, updateManga} from "@/api/mgApi";
import singleUpload from "@/components/upload/upload.vue";
import {uploadFile} from "@/api/fileApi";
import MangaEpTable from "@/components/manga/mangaEpTable.vue";
import MangaMemberTable from "@/components/manga/mangaMemberTable.vue";
import {queryJoinTeam} from "@/api/cnTeamApi";

export default {
  name: 'mangaTableDrawer',
  components: {MangaMemberTable, MangaEpTable, singleUpload},
  data() {
    let validateCover = (rule, value, callback) => {
      if (!this.coverFile && !this.mangaForm.coverUrl) {
        return callback(new Error('请上传封面'));
      } else {
        callback();
      }
    };
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入漫画名称'));
      } else {
        checkNameExist(value).then(res => {
          if (res.data) {
            callback(new Error('同名漫画已经有汉化组在烤啦'))
          }
        })
      }
      callback();
    };
    let validateTeam = (rule, value, callback) => {
      if (!this.mangaForm.tid) {
        return callback(new Error('请选择汉化组'));
      } else {
        callback();
      }
    }
    return {
      // 抽屉数据
      visible: false,
      sonDrawerVisible: false,
      loading: true,
      submitLoading: false,
      uploadLoading: false,
      mangaFormType: 'save',

      // 表格数据
      keyword: "",
      page: {
        page: 1,
        size: 10
      },
      total: 0,

      // 表单数据
      tableData: [],
      cnTeamList: [],
      coverFile: null,
      mangaForm: {
        name: '',
        author: '',
        tid: null,
        about: '',
        status: false,
        coverUrl: ''
      },
      mangaFormRules: {
        name: [{validator: validateName, trigger: 'blur'}],
        // cnTeam: [{required: true, message: '请选择汉化组', trigger: 'change'}],
        cnTeam: [{validator: validateTeam, trigger: 'change'}],
        cover: [{validator: validateCover, trigger: 'blur'}]
      }
    }
  },
  methods: {
    openWindow() {
      this.visible = true
      this.flashTable()
    },
    handleClose() {
      this.visible = false
      this.$emit('flashData')
    },
    handleSonClose(done) {
      this.$confirm('关闭后不会保存数据，是否关闭？')
          .then(() => {
            this.mangaForm = {
              name: '',
              author: '',
              cnTeam: '',
              about: '',
              status: false,
              coverUrl: ''
            }
            done();
          })
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.flashTable()
    },
    flashTable() {
      this.loading = true
      mineMangaPage(this.page, this.keyword, null)
          .then(res => {
            this.tableData = res.data.records
            this.total = Number(res.data.total)
            this.loading = false
          })
    },
    openSonDrawer(type, row) {
      this.mangaForm = row ? row : {}
      this.mangaFormType = type
      this.sonDrawerVisible = true
      this.getJoinTeam()
    },
    deleteManga(row) {
      this.$confirm('确认删除该漫画？', {
        type: 'warning',
      })
          .then(() => {
            deleted(row.mangaId).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.flashTable()
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                })
              }
            })
          })
    },
    changeStatus(row) {
      // 取反还原状态，防止真正修改前icon状态就变化
      row.isAvailable = !row.isAvailable
      this.$confirm('确认修改该漫画的展示状态？')
          .then(() => {
            // 因为前面取反还原展示状态了，所以传反的
            available(row.mangaId, !row.isAvailable).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.flashTable()
              } else {
                this.$message({
                  message: '操作失败',
                  type: 'error'
                })
              }
            })
          })
    },
    getJoinTeam() {
      queryJoinTeam().then(res => {
        this.cnTeamList = res.data
      })
    },
    /**
     * 获取封面
     * @param file
     */
    getCover(file) {
      this.coverFile = file
    },
    /**
     * 清理封面
     */
    cleanupCover() {
      this.coverFile = null
      this.mangaForm.coverUrl = ''
      this.mangaForm.thumbCoverUrl = ''
    },
    /**
     * 提交表单
     */
    submitMangaForm() {
      this.$refs.mangaForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          // 当封面文件不为空时
          if (this.coverFile) {
            // 上传封面
            const formData = new FormData();
            formData.append('prefix', 'cover/' + this.mangaForm.name);
            formData.append('datePrefix', false);
            formData.append('file', this.coverFile);
            this.uploadLoading = true
            let res = await uploadFile(formData)
            this.mangaForm.coverUrl = res.data
            this.uploadLoading = false
          }
          if (this.mangaFormType === 'save') {
            // 保存漫画
            saveManga(this.mangaForm).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '创建成功，快开烤吧',
                  type: 'success'
                })
                this.flashTable()
                this.sonDrawerVisible = false
                this.resetForm('mangaForm')
              } else {
                this.$message({
                  message: '创建失败',
                  type: 'error'
                })
              }
              this.submitLoading = false
            })
          } else {
            // 编辑漫画
            updateManga(this.mangaForm).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: '编辑成功',
                  type: 'success'
                })
                this.flashTable()
                this.sonDrawerVisible = false
                this.resetForm('mangaForm')
              } else {
                this.$message({
                  message: '编辑失败',
                  type: 'error'
                })
              }
              this.submitLoading = false
            })
          }
        }
      });
    },
    /**
     * 重置表单
     * @param formName 表单名称
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.mangaForm = {
        name: '',
        author: '',
        cnTeam: '',
        about: '',
        status: false,
        coverUrl: ''
      }
      this.$refs.cover.cleanup()
      this.submitLoading = false
    }
  }
}
</script>

<style scoped lang="scss">
#drawer-main-box {
  width: 100%;
  height: 100%;
  padding: 0 20px 0 20px;
  display: flex;
  flex-direction: column;
  justify-items: flex-start;

  .table-top {
    display: flex;
    width: 100%;
    align-items: center;
    justify-content: space-between;
  }

  ::v-deep .el-table__body-wrapper {
    /* 滚动条背景 */
    &::-webkit-scrollbar {
      width: 7px !important;
      height: 7px !important;
      border-radius: 5px !important;
      background-color: rgb(245, 245, 245, 0.5) !important;
    }

    /* 滑块 */
    &::-webkit-scrollbar-thumb {
      border-radius: 5px !important;
      background-color: var(--theme-color) !important;
    }
  }
}

#son-drawer-main-box {
  width: 100%;
  height: 100%;
  padding: 0 20px 0 20px;
  display: flex;
  flex-direction: column;
  justify-items: flex-start;

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

#table-box {
  margin-top: 10px;
  background-color: #f0f0f0; /* 设置背景色 */
  border: 1px solid #ccc; /* 边框 */
  border-radius: 5px; /* 圆角 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2), 0 -2px 5px rgba(0, 0, 0, 0.1); /* 上下两个外阴影，模拟立体感 */
}
</style>